#include "editortabwidget.h"

#include <QDebug>

EditorTabWidget::EditorTabWidget(QWidget *parent) :
    QTabWidget(parent)
{
    this->setTabsClosable(true);
    connect(this, SIGNAL(tabCloseRequested(int)), this, SLOT(onTabCloseRequested(int)));
}

TextEditor *EditorTabWidget::editor(int index) const
{
    return static_cast<TextEditor*>(QTabWidget::widget(index));
}

void EditorTabWidget::newEditor(QString filename)
{
    QString name = filename.right(filename.length() - filename.lastIndexOf("/") - 1);
    TextEditor * editor = new TextEditor(filename);

    int index = this->addTab(editor, QIcon(), name);
    this->setCurrentIndex(index);
    editor->setFocus();

    if(filename != "untitled") {
        QFile file(filename);
        file.open(QIODevice::ReadOnly | QIODevice::Text);
        editor->setPlainText(file.readAll());
        file.close();
    }

    connect(editor, SIGNAL(modificationChanged(bool)), this, SLOT(onTextChanged(bool)));
}

void EditorTabWidget::saveCurrentFile()
{
    this->editor(this->currentIndex())->saveFile();
    this->setTabText(this->currentIndex(), this->editor(this->currentIndex())->getFileName());
}

void EditorTabWidget::onTabCloseRequested(int index)
{
    this->setCurrentIndex(index);

    if(currentEditor()->document()->isModified()) {
        EditorExitDialog *exitDialog = new EditorExitDialog(currentEditor()->getFileName(), this);
        EditorExitDialog::ExitCode exitCode = exitDialog->exec();
        delete exitDialog;

        if(exitCode == EditorExitDialog::Save)
        {
            currentEditor()->saveFile();
            currentEditor()->close();
        }
        else if(exitCode == EditorExitDialog::Discard)
            currentEditor()->close();
        else
            return;
    }

    this->removeTab(currentIndex());
}

void EditorTabWidget::onTextChanged(bool modified)
{
    if(modified)
        setTabText(currentIndex(), tabText(currentIndex()) + "*");
    else {
        QString tmp = tabText(currentIndex());
        tmp.chop(1);
        setTabText(currentIndex(), tmp);
    }
}
